package cn.leaf.web.support;

import cn.leaf.common.entity.LoginUser;
import cn.leaf.common.util.SecurityUtil;
import cn.leaf.web.annotation.EnableUser;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 *
 * description: 通过header里的token获取用户信息
 *
 * @author twinkle leaf
 * @version v1.0.0
 * @since 2021-11-07 10:52:09
 * slogan: There are no two identical leaves in the world.
 *
 */
@Slf4j
@AllArgsConstructor
public class LoginUserArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        boolean isHasEnableUserAnn = parameter.hasParameterAnnotation(EnableUser.class);
        boolean isHasLoginUserParameter = parameter.getParameterType().isAssignableFrom(LoginUser.class);
        return isHasEnableUserAnn && isHasLoginUserParameter;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, @NonNull NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) {
        EnableUser user = methodParameter.getParameterAnnotation(EnableUser.class);
        if (null == user) {
            return null;
        }
        boolean value= user.value();
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        /**
         * 根据value状态获取更多用户信息，待实现
         */
        return SecurityUtil.getUsername(request);
    }
}
